/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 2; tab-width: 8 -*- */
/*
 * gtrpixcache.c
 * Copyright (C) Jonas Hagmar 2009 <gnotterdev@gmail.com>
 * 
 * gtrpixcache.c is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * gtrpixcache.c is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <glib.h>
#include <glib/gstdio.h>
#include <string.h>
#include <sys/stat.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include "twitter_api.h"

#define GTR_DIR "gnotter"
#define GTR_PIXCACHE_DIR "pixchache"

void
gtr_pixcache_init (void)
{
  gchar    *dir_name;
  gchar const *filename;
  gchar *filename_full;
  GDir *dir;

  dir_name = g_build_filename (g_get_user_cache_dir (), GTR_DIR, GTR_PIXCACHE_DIR, NULL);

  if (!g_file_test (dir_name, G_FILE_TEST_EXISTS|G_FILE_TEST_IS_DIR)) {
    g_mkdir_with_parents (dir_name, S_IRUSR|S_IWUSR|S_IXUSR);
  }
  else
  {
    dir = g_dir_open (dir_name, 0, NULL);
    filename = g_dir_read_name (dir);
    while (filename != NULL)
    {
      filename_full = g_build_filename (g_get_user_cache_dir (), GTR_DIR, GTR_PIXCACHE_DIR, filename, NULL);
      g_remove (filename_full);
      g_free (filename_full);
      filename = g_dir_read_name (dir);
    }
    g_dir_close (dir);
  }

  g_free (dir_name);
}

static gchar *
url_2_filename (char const *url)
{
  gchar *csum;
  gchar *filename;
  csum = g_compute_checksum_for_data (G_CHECKSUM_SHA256, (guchar*)url, strlen (url));
  filename = g_build_filename (g_get_user_cache_dir (), GTR_DIR, GTR_PIXCACHE_DIR, csum, NULL);
  g_free (csum);
  return (filename);
}

static void
cache_pic (char const *url, gchar const *filename)
{
  if (!g_file_test (filename, G_FILE_TEST_EXISTS))
  {
    twapi_http_get_to_file (url, filename);
  }
}

void
gtr_pixcache_cache_pic (char const *url)
{
  gchar *filename;

  filename = url_2_filename (url);
  cache_pic (url, filename);
  g_free (filename);
}

GdkPixbuf *
gtr_pixcache_get_pixbuf (char const *url)
{
  gchar *filename;
  GdkPixbuf *pixbuf;

  filename = url_2_filename (url);
  pixbuf = gdk_pixbuf_new_from_file_at_size (filename, 48, 48, NULL);
  g_free (filename);
  return pixbuf;
}